package cn.wolfcode.interceptor;

import cn.wolfcode.anno.RequiredPermission;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.utils.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService permissionService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取当前登录用户
        //Employee employee = (Employee) request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        Employee employee = UserContext.getCurrentUser();
        System.out.println("焦小波");
        //2、判断是否是超级管理员
        if(employee.isAdmin()){
            return true;
        }
        HandlerMethod handlerMethod=null;
        //3、获取到拦截的方法
        if(handler instanceof HandlerMethod){
            handlerMethod=(HandlerMethod)handler;
            RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
            if(annotation==null){
                return true;
            }
            //获取权限表达式
            String expression = annotation.expression();
            //获取当前登录用户拥有的权限表达式集合
            //List<String> list = (List<String>) request.getSession().getAttribute("EXPRESSION_IN_SESSION");
            List list = UserContext.getExpressions();
            System.out.println(list);
            if(list.contains(expression)){
                return true;
            }
        }
        //不包含
        if(!handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            //跳转到错误页面
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request, response);
        }else{
            //否则响应jason数据
            JsonResult jsonResult = new JsonResult("您没有权限访问，请联系管理员",false);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(jsonResult));
        }
        return false;
    }
}
